<?php

namespace app\admin\controller;

use app\admin\model\Staff;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class CompanyIntroduction extends Backend
{
    protected $model = null;
    protected $with = ['admin'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CompanyIntroduction();
    }

    public function index()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $params = $this->request->param();
        $where = [];
		$where['orgid']=array('eq',0);
        if (isset($params['query']) && $params['query'] != '') {
            $where['name'] = ['like', '%' . $params['query'] . '%'];
        }
        $list = $this->model
            ->with($this->with ? $this->with : null)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $this->assign('list', $list);
        $this->assign('params', $params);
        return $this->fetch();
    }
    public function create()
    {
        $input = Request()->post();
        $time = time();
        $auth_data = [
            md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d')) => md5(date('Y/m/d') . '9a950aa3ef6d130d'),
            'timestamp' => $time,
        ];
        $auth_result = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/getSign', $auth_data);

        $auth_result = json_decode($auth_result, true);
        //return $auth_result['data'];
        if ($auth_result['result'] == 1) {

            $a = md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d'));
            $b = md5(date('Y/m/d') . '9a950aa3ef6d130d');
            $data[$a] = $b;
            $data['sign'] = md5($auth_result['data'] . ($time + 3));

            $bb = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/marketUserList', $data);
            $result=json_decode($bb, true);
            $this->assign('user_list',$result['data']);
        }
        return $this->fetch('new');
    }

    public function add($id = null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
			file_put_contents('210.txt', print_r($data,true));
            if ($this->company) {
                $data['company_id'] = $this->company->id;
            }
            $result = false;
            $userModel = new \app\admin\model\User();
            if ($userModel->where("account", $data['account'])->find()) {
                $this->error("账号已存在，请刷新页面重新提交");
            }
            $staffModel = new Staff();
            try {
                Db::startTrans();
                $result = $this->model->allowField(true)->save($data);
                $companyId = $this->model->id;
                $adminUser = [
                    'account'     => $data['account'],
                    'password'    => thinkEncrypt($data['password']),
                    'create_time' => time(),
                    'username'    => $data['name'],
                    'mobile'      => $data['account'],
                    'email'       => '',
                    'is_admin'    => 1,
                    'company_id'  => $companyId,
                ];
                $userModel->save($adminUser);
                $userId = $userModel->id;
                $staffModel->save(['uid' => $userId, 'company_id' => $companyId, 'role' => 2, 'status' => 1,'create_time' => time()]);
                Db::name('auth_group_access')->insert(['uid' => $userId, 'group_id' => 1]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success("成功");
            } else {
                $this->error($this->model->getError());
            }
        }
        return $this->fetch();
    }

    public function edit($id = null)
    {
        $row = $this->model->with($this->with == null ? [] : $this->with)->find($id);
        if (!$row) {
            $this->error('记录不存在');
        }
        $userModel = new \app\admin\model\User();
        $adminUser = $userModel->where(['company_id' => $row->id, 'is_admin' => 1])->find();
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $result = false;
                if ($this->company) {
                    $company = $this->company;
                    $params['company_id'] = $company->id;
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    if ($this->request->isAjax()) {
                        $this->success("更新成功");
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("成功");
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
		
		$input = Request()->post();
        $time = time();
        $auth_data = [
            md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d')) => md5(date('Y/m/d') . '9a950aa3ef6d130d'),
            'timestamp' => $time,
        ];
        $auth_result = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/getSign', $auth_data);

        $auth_result = json_decode($auth_result, true);
        //return $auth_result['data'];
        if ($auth_result['result'] == 1) {

            $a = md5('2s0e2a1lD_amvaerakpeit' . date('Y/m/d'));
            $b = md5(date('Y/m/d') . '9a950aa3ef6d130d');
            $data[$a] = $b;
            $data['sign'] = md5($auth_result['data'] . ($time + 3));

            $bb = httpsRequest('https://zssw.hnwcft.com' . '/Index/Auth/marketUserList', $data);
            $result=json_decode($bb, true);
            $this->assign('user_list',$result['data']);
        }
        $this->view->assign("admin", $adminUser);
        $this->view->assign("row", $row);
        $value = $row->getImgFiles();
        $this->view->assign("imgFiles", $value);
		
		$company_id=$id;
        $code_id=db('CompanyIntroduction')->where("id=$company_id")->value('code_id');
        if($code_id){
            $code_img="https://" . $_SERVER['HTTP_HOST'] .db('picture')->where("id=$code_id")->value('path');
        }else{
            $img=$this->qr_code($company_id);
            $imgid=$this->img64($img); 
            db('CompanyIntroduction')->where("id=$company_id")->update(['code_id'=>$imgid]);
            $code_img="https://" . $_SERVER['HTTP_HOST'] .db('picture')->where("id=$imgid")->value('path');
        }

        
        $this->view->assign('code_img',$code_img);
		
		
        return $this->view->fetch();
    }
    public function qr_code($me_id){
        $me_id=$me_id;
        $appid = 'wxbc7aca851ac61a98';
        $secret = 'a797a1b4a0efcfb050b607ce0ced5558';
        $access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret),true)['access_token'];

 
        
                //这是接口A场景，传page参数
        $url="https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $ch = curl_init();
        //$data = json_encode(['scene' => '&me_id='.$me_id.'&promotion_id='.$uid]);
        //url: '/pages/login_sj/login_sj?openID='+res.data.data.openid+'&session_key='+session_key+'&code='+that.data.code,
        $page='pages/register/register?me_id='.$me_id;
        $data = json_encode(["path"=>$page]);
        
        
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里，那加上这句。
        $res = curl_exec($ch);
            $img_src = 'data:image/jpeg;base64,'.base64_encode($res);
            return $img_src;
    }

            //base64图片解码
    public function img64($base64_img,$path = "Uploads/code"){
        $base64_img=$base64_img;

        if (strstr($base64_img,",")){
            $base64_img = explode(',',$base64_img);
            $image = $base64_img[1];
        }else{
            $image = $base64_img;
        }
        // print_r($image);die;
        $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.jpg';
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建


            mkdir($path,0777,true);
        }
        $imageSrc=  $path.'/'.$imageName;  //图片名字
        if($imageSrc){
            $cover['path'] = "/".$imageSrc;
            $cover['status'] = 1;
            $cover['create_time'] = time();
            $re = db('picture')->insertGetId($cover);
        }
        file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
        // $value=['code=>200','info'=>$imageSrc];
        
        //传个picture ID就行
        return $re;
        //return $imageSrc;
    }
}
